//
//  ListViewController.swift
//  souyun
//
//  Created by SkyGrass on 16/5/26.
//  Copyright © 2016年 SkyGrass. All rights reserved.
//

import UIKit

class ListViewController: UIViewController,UITableViewDelegate{
    var searchword:String?
    var apiclient:NewApiClient?
    var showapirequest:ShowApiRequest?
    var listView:ListView?
    var listdata:Viewdatas?
    var waitView:WaitView?
    
    @IBAction func btnBack(sender: AnyObject) {
        self.presentingViewController!.dismissViewControllerAnimated(true, completion: nil)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.navigationController?.navigationBar.translucent = false
        listdata = Viewdatas()
        waitView = WaitView(frame: CGRect(x: 0 , y: 0, width: self.view.frame.width, height: self.view.frame.height))
        waitView?.labMsg.text = self.navigationItem.title
        
        self.view.addSubview(waitView!)
        
        showapirequest = ShowApiRequest(url: SHOWAPI_URL!, appId: SHOWAPI_APPID!, secret: SHOWAPI_SECRET!)
        apiclient = NewApiClient()
        
        apiclient?.search(showapirequest!, _searchword: self.searchword!, _pageindex: 1, _completionHandler: { (data,error) in
            if error?.code!  != 0 {
                HUD.show(self.view, message:error!.errMsg!)
                self.presentingViewController!.dismissViewControllerAnimated(true, completion: nil)
                return
            }
            if data!.count > 0 {
                self.navigationItem.title? = self.searchword!
                self.listdata = data!
                self.listView = ListView(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height), _data:self.listdata!)
                self.view.addSubview(self.listView!)
                self.waitView?.hidden = true
                self.listView?.list.delegate = self
            }else{
                HUD.show(self.view, message:error!.errMsg!)
            }
        })
    }
    
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        let url = listdata![indexPath.row].url!
        let controller:WebViewController = WebViewController()
        controller.url = url
        self.navigationController?.pushViewController(controller, animated: true)
    }
}
